package com.fengdi.book.hard.design;

import java.util.LinkedHashMap;

class LRUCache {
    private LinkedHashMap<Integer, Integer> container;
    private final int capacity;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.container = new LinkedHashMap<>();
    }

    public int get(int key) {
        if(!this.container.containsKey(key)) {
            return -1;
        }
        this.makeRecentElement(key);
        return this.container.get(key);
    }

    public void put(int key, int value) {
        //当前元素存在
        if(this.container.containsKey(key)) {
            this.container.put(key, value);
            this.makeRecentElement(key);
            return;
        }

        // 当前元素不存在
        if(this.container.size() >= this.capacity) { //超过总容量无法直接插入
            Integer k = this.container.keySet().iterator().next();// 通过迭代器获取首个元素
            this.container.remove(k); // 移除
        }
        this.container.put(key, value);
    }

    private void makeRecentElement(Integer key) {
        Integer value = this.container.get(key);
        this.container.remove(key);
        this.put(key, value);
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
